package com.icesoft.core.web.suppose.safehttp.filter.impl;

import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.helper.ResponseUtils;
import com.icesoft.core.web.suppose.safehttp.filter.HeadSafeRequestFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class ContentTypeFilter implements HeadSafeRequestFilter {
    static String XMLHttpRequest = "XMLHttpRequest";

    @Override
    public boolean headFilter(HttpServletRequest request, HttpServletResponse response) {
        String xRequestedWith = request.getHeader("x-requested-with");
        if (!XMLHttpRequest.equals(xRequestedWith)) {
            String errMsg = "错误的请求头x-requested-with：" + xRequestedWith + "，请设置请求头x-requested-with：" + XMLHttpRequest;
            log.info(errMsg);
            ResponseUtils.writeJson(response, Resp.error(errMsg));
            return false;
        }
        if ("GET".equals(request.getMethod())) {
            return true;
        }
        String contentType = request.getContentType();
        if (StringUtils.isBlank(contentType)) {
            ResponseUtils.writeJson(response, Resp.error("contentType不能为空"));
            return false;
        }
        if (contentType.toLowerCase().startsWith(MediaType.APPLICATION_FORM_URLENCODED_VALUE.toLowerCase())) {
            String errMsg = "错误的请求头contentType：" + contentType;
            log.info(errMsg);
            ResponseUtils.writeJson(response, Resp.error(errMsg));
            return false;
        }
        return true;
    }
}
